﻿
Imports System.Threading

'for mono debug purpose,
'but the perf is a little bit better than .net framework TheadStatic attribute,
'since this class does not do boxing, so it may not work as expected with value type
Public Class thread_static(Of T)
    Private ReadOnly slot() As T
    Private ReadOnly size As Int32

    Public Sub New(ByVal size As Int32)
        k_assert(size > 0)
        ReDim slot(size - 1)
        Me.size = size
    End Sub

    Public Sub New()
        Me.New(constants.thread_static_default_slot_size)
    End Sub

    Private Function current_slot_id(ByRef o As Int32) As Boolean
        o = Thread.CurrentThread().ManagedThreadId() - 1
        Return o >= 0 AndAlso o < size
    End Function

    Public Function [get](ByRef o As T) As Boolean
        Dim tid As Int32 = 0
        If current_slot_id(tid) Then
            o = slot(tid)
            Return True
        Else
            Return False
        End If
    End Function

    Public Function [get]() As T
        Dim o As T = Nothing
        k_assert([get](o))
        Return o
    End Function

    Public Function [set](ByVal i As T) As Boolean
        Dim tid As Int32 = 0
        If current_slot_id(tid) Then
            slot(tid) = i
            Return True
        Else
            Return False
        End If
    End Function

    Public Shared Operator +(ByVal this As thread_static(Of T)) As T
        If this Is Nothing Then
            Return Nothing
        Else
            Return this.get()
        End If
    End Operator
End Class
